package com.audi.adapter;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Switch;

import android.widget.TextView;
import android.widget.Toast;

import com.audi.R;
import com.audi.R.drawable;
import com.audi.BaseActivity;
import com.audi.activity.DeviceDetailActivity;
import com.audi.activity.HomeControlActivity;
import com.audi.dto.DeviceItem;
import com.audi.message.ActionMessage;
import com.audi.message.SendMessage;
import com.audi.utils.DeviceHelper;
import com.audi.view.DeviceUpdatePhoto;
import com.audi.view.MySlidingDrawer;

public class ListDeviceCardAdapterBottom extends BaseAdapter {
	private Activity mActivity;
	private DeviceUpdatePhoto mDeviceUpdatePhoto;
	private ArrayList<DeviceItem> mdeviceCardList;
	ImageView menudevicecard;
	private PopupMenu mPopMenu;
	public SendMessage sendMessage = new SendMessage();

	public ListDeviceCardAdapterBottom(Activity activity,
			ArrayList<DeviceItem> devicecradList,
			DeviceUpdatePhoto mDeviceUpdatePhoto) {
		mActivity = activity;
		mdeviceCardList = devicecradList;
		
		Log.d("log", "Checkstyle");
		this.mDeviceUpdatePhoto = mDeviceUpdatePhoto;
	}

	@Override
	public int getCount() {
		return mdeviceCardList.size();
	}

	@Override
	public DeviceItem getItem(int position) {
		Log.d("log", "Checkstyle");
		return mdeviceCardList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(int position, View convertView, ViewGroup view) {
		
		
		DeviceItem item = mdeviceCardList.get(position);
		ViewHolderBottom viewholder = null;
         
		// khoi tao cho viewholder
		if (convertView == null) {
			viewholder = new ViewHolderBottom();
			convertView = LayoutInflater.from(mActivity).inflate(
					R.layout.row_device_card_bot_new, null);

			viewholder.nameDevice = (TextView) convertView
					.findViewById(R.id.typeOfDeviceBot_addnew);
			viewholder.frameOnOff = (FrameLayout) convertView
					.findViewById(R.id.frame_onoff_addnew);

			viewholder.txtTemp = (TextView) convertView
					.findViewById(R.id.txt_temp_addnew);

			
			viewholder.imageMenu = (ImageView) convertView
					.findViewById(R.id.imv_device_tab_menu_bot_addnew);

			viewholder.placeName = (TextView) convertView
					.findViewById(R.id.placeNameDeviceBot_addnew);

			/*
			 * viewholder.slidingDrawer = (MySlidingDrawer) convertView
			 * .findViewById(R.id.slidingDrawer_addnew);
			 */
			viewholder.switchDrawer = (Switch) convertView
					.findViewById(R.id.mySwitch);

			viewholder.imageWarning = (ImageView) convertView
					.findViewById(R.id.img_warning_addnew);

			viewholder.img1 = (ImageView) convertView
					.findViewById(R.id.imageView100);
			viewholder.img2 = (ImageView) convertView
					.findViewById(R.id.imageView101);
			viewholder.imgTemp = (ImageView) convertView
					.findViewById(R.id.img_temp_addnew);
			viewholder.layoutTemp = (FrameLayout) convertView
					.findViewById(R.id.layout_temp_addnew);
			viewholder.imageWarning.setVisibility(View.GONE);

			viewholder.layoutTemp.setVisibility(View.GONE);
			viewholder.frameOnOff.setVisibility(View.GONE);
			viewholder.img1.setVisibility(View.INVISIBLE);
			viewholder.img2.setVisibility(View.INVISIBLE);

			convertView.setTag(viewholder);
		} else {
			viewholder = (ViewHolderBottom) convertView.getTag();
		}
		// set data for listView
		int deviceType = DeviceHelper.getGroupType(item.getDeviceType());
		if (deviceType == 0) {

			viewholder.imageWarning.setVisibility(View.GONE);

			viewholder.layoutTemp.setVisibility(View.GONE);
			viewholder.frameOnOff.setVisibility(View.VISIBLE);
			// viewholder.slidingDrawer.setVisibility(View.VISIBLE);
			viewholder.switchDrawer.setOnCheckedChangeListener(null);
			if (item.getDeviceStatus() == 1) {

				
				viewholder.switchDrawer.setChecked(false);
				viewholder.switchDrawer
						.setBackgroundResource(R.drawable.icon_decive_on_small_source);
				viewholder.img1.setVisibility(View.VISIBLE);
				viewholder.img2.setVisibility(View.INVISIBLE);
				
			} else {
				viewholder.switchDrawer.setChecked(true);
				viewholder.switchDrawer
						.setBackgroundResource(R.drawable.icon_device_off_small);

				viewholder.img1.setVisibility(View.INVISIBLE);
				viewholder.img2.setVisibility(View.VISIBLE);
			}
		} else if (deviceType == 1) {

			viewholder.frameOnOff.setVisibility(View.GONE);
			viewholder.imageWarning.setVisibility(View.VISIBLE);
			viewholder.layoutTemp.setVisibility(View.GONE);
			if (item.getDeviceStatus() == 1) {
				viewholder.imageWarning
						.setImageResource(R.drawable.icon_warning_sensor_green);
			} else {
				viewholder.imageWarning
						.setImageResource(R.drawable.icon_warning_sensor_red);
			}
		} else {

			viewholder.frameOnOff.setVisibility(View.GONE);
			viewholder.imageWarning.setVisibility(View.GONE);
			viewholder.layoutTemp.setVisibility(View.VISIBLE);

			viewholder.imgTemp.setImageResource(R.drawable.temp_icon_small);
			viewholder.txtTemp.setVisibility(View.VISIBLE);
			viewholder.txtTemp.setText(item.getDeviceStatus() + "");
		}

		viewholder.nameDevice.setText(item.getDeviceName());

		viewholder.placeName.setText(item.getDevicePlace());
         
         
		onclick(viewholder, position, convertView);

		return convertView;
	}

	
	public void onclick(final ViewHolderBottom viewholder, final int position,
			final View convertView) {
         
		final DeviceItem ItemCurrent = mdeviceCardList.get(position);
		
		viewholder.switchDrawer
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked == false) {
							Log.d("switch1", "Open");
							viewholder.switchDrawer
									.setBackgroundResource(R.drawable.icon_decive_on_small_source);

							viewholder.img1.setVisibility(View.VISIBLE);
							viewholder.img2.setVisibility(View.INVISIBLE);
							DeviceItem newItemOpen = new DeviceItem();
							  newItemOpen.setDeviceId(ItemCurrent.getDeviceId());
							  newItemOpen.setDeviceStatus(1);
							sendMessage.sendData(ActionMessage.UPDATE_DEVICE, newItemOpen, handlerUpdateDevice);

						} else {
							Log.d("switch2", "Close");
							viewholder.switchDrawer
									.setBackgroundResource(R.drawable.icon_device_off_small);

							viewholder.img1.setVisibility(View.INVISIBLE);
							viewholder.img2.setVisibility(View.VISIBLE);
							DeviceItem newItemOpen = new DeviceItem();
							  newItemOpen.setDeviceId(ItemCurrent.getDeviceId());
							  newItemOpen.setDeviceStatus(0);
							sendMessage.sendData(ActionMessage.UPDATE_DEVICE, newItemOpen, handlerUpdateDevice);
						}
					}
				});
	
		viewholder.switchDrawer
				.setOnLongClickListener(new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
						DeviceItem item1 = ItemCurrent;
						ClipData.Item item = new ClipData.Item(item1
								.getDeviceId() + "");

						String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
						ClipData dragData = new ClipData(convertView.getTag()
								+ "", clipDescription, item);
						// ClipData dragData = new ClipData(v.getId()+"",
						// clipDescription, item);
						Log.e("============",
								"======drfdf===" + convertView.getTag());

						DragShadowBuilder myShadow = new HomeControlActivity.MyDragShadowBuilder(
								convertView);

						convertView.startDrag(dragData, // ClipData
								myShadow, // View.DragShadowBuilder
								item1.getDeviceId(), // Object myLocalState
								0); // flags
						return true;
					}
				});
		viewholder.imageMenu
		.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				DeviceItem item1 = ItemCurrent;
				ClipData.Item item = new ClipData.Item(item1
						.getDeviceId() + "");

				String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
				ClipData dragData = new ClipData(convertView.getTag()
						+ "", clipDescription, item);
				// ClipData dragData = new ClipData(v.getId()+"",
				// clipDescription, item);
				Log.e("============",
						"======drfdf===" + convertView.getTag());

				DragShadowBuilder myShadow = new HomeControlActivity.MyDragShadowBuilder(
						convertView);

				convertView.startDrag(dragData, // ClipData
						myShadow, // View.DragShadowBuilder
						item1.getDeviceId(), // Object myLocalState
						0); // flags
				return true;
			}
		});
		
		viewholder.imageMenu.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				mPopMenu = new PopupMenu(mActivity, viewholder.imageMenu);
				mPopMenu.getMenuInflater().inflate(
						R.menu.menu_list_device_card, mPopMenu.getMenu());
				mPopMenu.show();
				mPopMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
					// check style
					@Override
					public boolean onMenuItemClick(MenuItem index) {
						// TODO Auto-generated method stub
						if (index.getItemId() == R.id.deviceMenu_editName) {

							((HomeControlActivity) mActivity)
									.renameDeviceFuntion(ItemCurrent);
							// check style
							// Toast.makeText(mActivity, "Changed!", 1).show();
						}
						if (index.getItemId() == R.id.deviceMenu_editPlace) {
							// Toast.makeText(mActivity, "Changed!", 1).show();

							((HomeControlActivity) mActivity)
									.changePlaceDeviceFuntion(ItemCurrent);

						}
						if (index.getItemId() == R.id.deviceMenu_editPhoto) {
							// Toast.makeText(mActivity, "Edited!", 1).show();

							((HomeControlActivity) mActivity)
									.changePhotoDeviceFuntion(ItemCurrent);

						}
						if (index.getItemId() == R.id.deviceMenu_delete) {

							((HomeControlActivity) mActivity)
									.deleteDeviceFuntion(ItemCurrent);

							// Toast.makeText(mActivity, "Deleted!", 1).show();
						}
						return true;
					}
				});

			}
		});
		viewholder.nameDevice
		.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				DeviceItem item1 = ItemCurrent;
				ClipData.Item item = new ClipData.Item(item1
						.getDeviceId() + "");

				String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
				ClipData dragData = new ClipData(convertView.getTag()
						+ "", clipDescription, item);
				// ClipData dragData = new ClipData(v.getId()+"",
				// clipDescription, item);
				Log.e("============",
						"======drfdf===" + convertView.getTag());

				DragShadowBuilder myShadow = new HomeControlActivity.MyDragShadowBuilder(
						convertView);

				convertView.startDrag(dragData, // ClipData
						myShadow, // View.DragShadowBuilder
						item1.getDeviceId(), // Object myLocalState
						0); // flags
				return true;
			}
		});
		viewholder.nameDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intentDeviceCard = new Intent(mActivity,
						DeviceDetailActivity.class);
				Bundle bundleInfoDevice = new Bundle();

				bundleInfoDevice.putSerializable("item", ItemCurrent);

				intentDeviceCard.putExtras(bundleInfoDevice);
				mActivity.startActivity(intentDeviceCard);

			}
		});
		viewholder.placeName
		.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				DeviceItem item1 = ItemCurrent;
				ClipData.Item item = new ClipData.Item(item1
						.getDeviceId() + "");

				String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
				ClipData dragData = new ClipData(convertView.getTag()
						+ "", clipDescription, item);
				// ClipData dragData = new ClipData(v.getId()+"",
				// clipDescription, item);
				Log.e("============",
						"======drfdf===" + convertView.getTag());

				DragShadowBuilder myShadow = new HomeControlActivity.MyDragShadowBuilder(
						convertView);

				convertView.startDrag(dragData, // ClipData
						myShadow, // View.DragShadowBuilder
						item1.getDeviceId(), // Object myLocalState
						0); // flags
				return true;
			}
		});
		viewholder.placeName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent intentDeviceCard = new Intent(mActivity,
						DeviceDetailActivity.class);
				Bundle bundleInfoDevice = new Bundle();

				bundleInfoDevice.putSerializable("item", ItemCurrent);

				intentDeviceCard.putExtras(bundleInfoDevice);
				mActivity.startActivity(intentDeviceCard);

			}
		});

	}
	static class ViewHolderBottom {
		private FrameLayout frameOnOff;

		private TextView nameDevice;

		private TextView placeName;
		// private TextView placeNameDevice;
		private ImageView imageMenu;
		
		private Switch switchDrawer;
		private ImageView imageWarning;
		private FrameLayout layoutTemp;
		private TextView txtTemp;
		private ImageView imgTemp, img1, img2;

	}

	public void swapItems(ArrayList<DeviceItem> mList) {
		this.mdeviceCardList = mList;
		notifyDataSetChanged();
	}

	/**
	 * handlerRenamePrivacyDeletePlace
	 * 
	 * @see update UI place
	 */
	@SuppressLint("HandlerLeak")
	private android.os.Handler handlerUpdateDevice = new android.os.Handler() {

		public void handleMessage(final Message msg) {
			mActivity.runOnUiThread(new Runnable() {
				public void run() {
					try {
						if (msg.arg1 != -1) {
							// status
							if (msg.getData()
									.getInt(String
											.valueOf(ActionMessage.UPDATE_DEVICE)) > 0) {
								Log.d("update device", "OK!!!!");
								((BaseActivity) mActivity).onRefreshData();
							} 
						}
					} catch (Exception e) {
					}
				}
			});
		}
	};
}
